package ChatRoom;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class chatRoomFacade {
	private static Connection connect() throws SQLException, ClassNotFoundException {
		String username = "root";
		String password = "tjappie2007";
		String url = "jdbc:mysql://localhost/chatroom";
		Class.forName("com.mysql.jdbc.Driver");
		Connection conn = DriverManager.getConnection(url, username, password);
		return conn;
	}
	
	public static void update(chatlog log) throws SQLException, ClassNotFoundException {
		Connection conn = null;
		try {
			conn = connect();
			Statement stat = conn.createStatement();
			stat.executeUpdate("create table if not exists chatlog(id bigint unsigned not null auto_increment, name char(20), timestamp bigint, text char(200), primary key (id));");
			PreparedStatement prep = conn.prepareStatement("insert into chatlog values (?, ?, ?, ?);");
			prep.setString(1, null);
			prep.setString(2, log.getUsername());
			prep.setLong(3, log.getTimestamp());
			prep.setString(4, log.getText());
			prep.execute();
			//conn.commit();
		} finally {
			conn.close();
		}
	}
	
	@SuppressWarnings("unchecked")
	public static List<chatlog> getRecent(String userName, long startTime) throws SQLException, ClassNotFoundException {
		Connection conn = null;
		List<chatlog> result = new ArrayList();
		try {
			conn = connect();
			Statement stat = conn.createStatement();
			ResultSet rs = stat.executeQuery("select * from chatlog where timestamp >= " + startTime + " order by timestamp");
			while (rs.next()) {
				String name = rs.getString("name");
				if (name.equals(userName)) {
					name = "Me";
				}
				chatlog log = new chatlog(name, rs.getLong("timestamp"), rs.getString("text"));
				result.add(log);
			}
		} finally {
			conn.close();
		}
		return result;
	}
}
